import { Card, message, Row, Col, Space, Divider, Descriptions } from 'antd';
import ProForm, {
  ProFormTextArea,
  ProFormSelect,
  ProFormDatePicker,
  ProFormDependency,
  ProFormUploadButton,
  ProFormGroup,
} from '@ant-design/pro-form';
import type { FC } from 'react';
import { useRequest, history } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import { addRecordCase, queryCaseDetail, updateRecord, queryRecordDetail } from './servic';
import {
  hospitalDeptlist,
  hospitalList,
  queryUserVisitors,
  doctorList,
} from '@/services/ant-design-pro/api';

const BasicForm: FC<Record<string, any>> = () => {
  const { caseId } = history.location.query;
  const { data } = useRequest(() => {
    if (caseId) {
      return queryCaseDetail({ id: caseId });
    }
  });

  const onFinish = async (values: Record<string, any>) => {
    console.log('values', values);
    if (values.doctor) {
      values.doctorId = values.doctor.value;
      values.doctorName = values.doctor.label;
      delete values.doctor;
    }
    if (values.dept) {
      values.deptId = values.dept.value;
      values.deptName = values.dept.label;
      delete values.dept;
    }
    if (values.hospital) {
      values.hospitalId = values.hospital.value;
      values.hospitalName = values.hospital.label;
      delete values.hospital;
    }
    if (values.visitor) {
      values.visitorId = values.visitor.value;
      values.visitorName = values.visitor.label;
      delete values.visitor;
    } else {
      values.visitorId = data.visitorId;
      values.visitorName = data.visitorName;
    }

    if (values.upload[0].response) {
      let filesUrl = '';
      for (var i = 0; i < values.upload.length; i++) {
        filesUrl += values.upload[i].response.data.url + ',';
      }
      values.filesUrl = filesUrl.substring(0, filesUrl.length - 1);
      delete values.upload;
    }
    console.log('values111', values);

    if (history.location.query.id) {
      values.id = history.location.query.id;
      try {
        const response = await updateRecord(values);
        if (response.code == 200) {
          message.success('修改成功');
        } else {
          message.error('修改失败!');
        }
      } catch (error) {
        console.log(error);
      }
    } else {
      try {
        const response = await addRecordCase(values);
        if (response.code == 200) {
          message.success('添加成功');
        } else {
          message.error('添加失败!');
        }
      } catch (error) {
        console.log(error);
      }
    }
  };

  const formItemLayout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 14 },
  };

  return (
    <PageContainer content="">
      <Card bordered={false}>
        <ProForm
          hideRequiredMark
          style={{ margin: 'auto', marginTop: 8 }}
          name="basic"
          layout="horizontal"
          request={async () => {
            if (history.location.query.id) {
              return queryRecordDetail(history.location.query).then(({ data }) => {
                let doctor = {
                  value: data.doctorId,
                  label: data.doctorName,
                  key: data.doctorId,
                };
                data.doctor = doctor;

                let dept = {
                  value: data.deptId,
                  label: data.deptName,
                  key: data.deptId,
                };
                data.dept = dept;

                let hospital = {
                  value: data.hospitalId,
                  label: data.hospitalName,
                  key: data.hospitalId,
                };
                data.hospital = hospital;
                data.addUserType = data.addUserType + '';

                if (data.filesUrl) {
                  let uploads = data.filesUrl.split(',');
                  let upload = [];
                  if (uploads.length > 0) {
                    for (var i = 0; i < uploads.length; i++) {
                      let obj = {
                        uid: i,
                        name: 'filesUrl' + i,
                        status: 'done',
                        url: uploads[i],
                      };
                      upload.push(obj);
                    }
                    data.upload = upload;
                  }
                }
                console.log('data', data);
                return data;
              });
            } else {
              return {};
            }
          }}
          onFinish={onFinish}
          {...formItemLayout}
          submitter={{
            render: (props, doms) => {
              return (
                <Row>
                  <Col span={14} offset={4}>
                    <Space>{doms}</Space>
                  </Col>
                </Row>
              );
            },
          }}
        >
          {caseId ? (
            <Descriptions
              column={1}
              labelStyle={{
                // color: '#787A7D',
                width: '150px',
                marginRight: '10px',
                display: 'block',
                textAlign: 'right',
              }}
            >
              <Descriptions.Item label="就诊人">{data ? data.visitorName : ''}</Descriptions.Item>
              <Descriptions.Item label="性别">
                {data && data.sex == 1 ? '男' : '女'}
              </Descriptions.Item>
              <Descriptions.Item label="出生日期">
                {data ? data.userBirthday : ''}
              </Descriptions.Item>
            </Descriptions>
          ) : null}
          {caseId ? <Divider /> : null}
          {caseId ? (
            <Descriptions
              column={1}
              labelStyle={{
                // color: '#787A7D',
                width: '150px',
                marginRight: '10px',
                display: 'block',
                textAlign: 'right',
              }}
            >
              <Descriptions.Item label="疾病">{data ? data.diseaseName : ''}</Descriptions.Item>
              <Descriptions.Item label="确诊时间">
                {data ? data.confirmedTime : ''}
              </Descriptions.Item>
              <Descriptions.Item label="病理分型">
                {data ? data.pathologyType : ''}
              </Descriptions.Item>
              <Descriptions.Item label="肿瘤分期">
                {data ? data.tumorStageT + data.tumorStageN + data.tumorStageM : ''}
              </Descriptions.Item>
              <Descriptions.Item label="是否转移">
                {data && data.metastasis == 1 ? data.metastasisSite : '否'}
              </Descriptions.Item>
              <Descriptions.Item label="病历更新时间">
                {data ? data.updateTime : ''}
              </Descriptions.Item>
            </Descriptions>
          ) : (
            <ProFormSelect
              width="md"
              name="visitor"
              label="就诊人"
              fieldProps={{
                labelInValue: true,
              }}
              showSearch
              request={async ({ keyWords }) => {
                let query = {
                  likeQuery: {
                    visitorName: keyWords,
                  },
                  pageNum: 1,
                  pageSize: 20,
                };
                return queryUserVisitors(query).then(({ data }) => {
                  return data.records.map((item) => {
                    return {
                      label: item.visitorName,
                      value: item.id,
                    };
                  });
                });
              }}
            />
          )}
          <Divider />
          <ProFormSelect
            width="md"
            name="hospital"
            label="就诊医院"
            showSearch
            fieldProps={{
              labelInValue: true,
            }}
            request={async ({ keyWords }) => {
              let query = {
                likeQuery: {
                  name: keyWords,
                },
                pageNum: 1,
                pageSize: 20,
              };
              return hospitalList(query).then(({ data }) => {
                return data.list.map((item) => {
                  return {
                    label: item.name,
                    value: item.id,
                  };
                });
              });
            }}
          />
          <ProForm.Item label="就诊科室" name="content">
            <ProFormDependency name={['hospital']}>
              {({ hospital }) => {
                return (
                  <ProFormGroup
                    key={hospital?.value}
                    // params={{
                    //   key: hospital?.value,
                    // }}
                  >
                    <ProFormSelect
                      width="150px"
                      params={{
                        key: hospital?.value,
                      }}
                      name="dept"
                      showSearch
                      fieldProps={{
                        labelInValue: true,
                      }}
                      request={async () => {
                        console.log('hospital', hospital);
                        let query = {
                          eqQuery: {
                            hospitalId: hospital.key,
                            level: 1,
                          },
                          pageNum: 1,
                          pageSize: 20,
                        };

                        // let arr = user.split('-');
                        return hospitalDeptlist(query).then(({ data }) => {
                          return data.list.map((item) => {
                            return {
                              label: item.name,
                              value: item.id,
                            };
                          });
                        });
                      }}
                    />
                    <ProFormDependency name={['dept']}>
                      {({ dept }) => {
                        return (
                          <ProFormSelect
                            params={{
                              key: dept?.value,
                            }}
                            width="150px"
                            name="deptSecond"
                            fieldProps={{
                              labelInValue: true,
                            }}
                            request={async () => {
                              // let arr = user.split('-');
                              let query = {
                                eqQuery: {
                                  parentId: dept.key,
                                },
                                pageNum: 1,
                                pageSize: 20,
                              };
                              return hospitalDeptlist(query).then(({ data }) => {
                                return data.list.map((item) => {
                                  return {
                                    label: item.name,
                                    value: item.id,
                                  };
                                });
                              });
                            }}
                          />
                        );
                      }}
                    </ProFormDependency>
                  </ProFormGroup>
                );
              }}
            </ProFormDependency>
          </ProForm.Item>
          <ProFormDependency name={['dept', 'deptSecond', 'hospital']}>
            {({ dept, deptSecond, hospital }) => {
              if (dept && deptSecond && hospital) {
                return (
                  <ProFormSelect
                    width="md"
                    params={{
                      key: dept?.value,
                    }}
                    name="doctor"
                    label="就诊医生"
                    showSearch
                    fieldProps={{
                      labelInValue: true,
                    }}
                    request={async () => {
                      console.log('dept', dept);
                      console.log('deptSecond', deptSecond);
                      console.log('hospital', hospital);
                      let query = {
                        hospitalId: hospital.value,
                        deptFirstId: dept.value,
                        deptSecondId: deptSecond.value,
                        pageNum: 1,
                        pageSize: 20,
                      };
                      console.log('query', query);
                      // let arr = user.split('-');
                      return doctorList(query).then(({ data }) => {
                        return data.records.map((item) => {
                          return {
                            label: item.name,
                            value: item.id,
                          };
                        });
                      });
                    }}
                  />
                );
              }
            }}
          </ProFormDependency>
          <ProFormDatePicker name="visitDate" label="就诊日期" width="md" />
          <ProFormTextArea
            name="visitReason"
            width="md"
            label="就诊原因"
            placeholder="请输入就诊原因"
          />
          <ProFormTextArea
            name="diagnosticResult"
            width="md"
            label="诊断结果"
            placeholder="请输入诊断结果"
          />
          <ProFormTextArea name="effect" width="md" label="治疗效果" placeholder="请输入治疗效果" />
          <ProFormUploadButton
            name="upload"
            label="图片资料"
            // max={1}
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
            }}
            action="/api/file/upload"
          />
          {/* <ProFormText
            width="md"
            label="案例文章"
            name="articleId"
            rules={[
              {
                required: true,
                message: '请输入文章id',
              },
            ]}
            placeholder="请输入文章id"
          /> */}
          {/* <ProFormRadio.Group
            options={[
              {
                value: '0',
                label: '用户',
              },
              {
                value: '1',
                label: '医生',
              },
              {
                value: '2',
                label: '系统',
              },
            ]}
            label="记录添加人"
            name="addUserType"
          />
          <ProFormDependency name={['addUserType']}>
            {({ addUserType }) => {
              if (addUserType != 2) {
                return (
                  <ProFormText
                    width="md"
                    label=" "
                    name="addUserId"
                    rules={[
                      {
                        required: true,
                        message: '请输入用户id',
                      },
                    ]}
                    placeholder="请输入用户id"
                  />
                );
              }
            }}
          </ProFormDependency> */}
        </ProForm>
      </Card>
    </PageContainer>
  );
};

export default BasicForm;
